
#include "Interface/Menu.h"

namespace Interface {

Menu::MenuEntry::MenuEntry(const Misc::Frame & frame, std::string entryName) : frame(frame), entryName(entryName)  {
}

// Menu entry have focus.
void Menu::MenuEntry::haveFocus(bool focused) {
}

Menu::MenuEntry::~MenuEntry() {
}

Menu::Menu(const Misc::Frame & frame, Uint16 size) : 
	frame(frame),
	entries(size, NULL),
	focus(0)  {
}

Menu::~Menu() {
}

//Focus an adjacent entry
void Menu::focusNext() {
	if (menuHidden || !menuActive) return;
	Sint16 i = focus;
	if (focus >= 0 && focus < (Sint16)entries.size() && entries[focus] != NULL && !entries[focus]->hidden() && entries[focus]->active())
		entries[focus]->haveFocus(false);
	for (i = focus+1; i < (Sint16)entries.size(); i++) {
		if (entries[i] != NULL) {
			focus = i;
			break;
		}
	}
    if ((i >= (Sint16)entries.size())) { /* Found nothing */
        if (focus == -1) return; // Found nothing from the beginning. Give-up
        else {
            // retry
            focus = -1;
            focusNext();
        }
	} else {
		if (!entries[focus]->hidden() && entries[focus]->active()) entries[focus]->haveFocus(true); // found something. focus it.
		else focusNext();
	}
}

//Focus an adjacent entry
void Menu::focusPrevious() {
  if (menuHidden || !menuActive) return;
  
	Sint16 i = focus;
	if (focus >= 0 && focus < (Sint16)entries.size() && entries[focus] != NULL && !entries[focus]->hidden() && entries[focus]->active())
		entries[focus]->haveFocus(false);
	for (i = focus-1; i >= 0; i--) {
		if (entries[i] != NULL) {
			focus = i;
			break;
		}
	}
	if ((i < 0)) { /* Found nothing */
		if (focus == (Sint16)entries.size()) return; // Found nothing from the end. Give-up
		else {
			// retry
			focus = entries.size();
			focusPrevious();
		}
	} else {
		if (!entries[focus]->hidden() && entries[focus]->active()) entries[focus]->haveFocus(true); // found something. focus it.
		else focusPrevious();
	}
}


} // namespace Interface
